<template>
  <a-select style="width: 360px;" v-model="myValue" @change="handleChange">
    <a-select-option v-for="item in candidateList" :key="item.userid" :value="item.userid">
      {{ item.fullname }}
    </a-select-option>
  </a-select>
</template>
<script>
import { queryCandidateusers } from '@/api/workflow/wf_YjaprvFlowable.js'
import { getCandiddataUser, setCandiddataUser } from '@/utils/formassembly/util.js'
import { CANDIDATE_USER } from '@/utils/custom/custom-candidate.js'
export default {
  props: {
    // 流程变量
    variable: {
      typeof: String,
      require: true,
    },
    // applyid
    applyid: {
      typeof: String,
      require: true,
    },
    // 候选组
    groupList: {
      typeof: Array,
      require: true,
    },
    // 候选用户
    userList: {
      typeof: Array,
      require: true,
    },
  },
  data() {
    return {
      myValue: undefined, // 默认值
      candidateList: null, // 候选列表
    }
  },
  created() {
    this.getCandidateusers(this.applyid, this.groupList, this.userList)
  },
  methods: {
    // 下拉触发
    handleChange(value) {
      setCandiddataUser(this.variable, value)
      this.$emit('f_setVariable', this.variable, value)
    },
    // 查询候选人
    getCandidateusers(applyid, groupList, userList) {
      queryCandidateusers(applyid, groupList, userList).then((res) => {
        if (res.code == 0) {
          if (res.data && res.data.length > 0) {
            // 优先看有没有配置默认环节候选人
            console.log('默认候选人', this.variable)

            // 优先从默认配置取, 取不到从缓存取
            let userid = null
            if(this.variable in CANDIDATE_USER) {
              userid = CANDIDATE_USER[this.variable]
            } else {
              // 1. 从缓存取看看之前有没有选过
              userid = getCandiddataUser(this.variable)
            }
            
            if (userid) {
              // 1.1. 校验之前选过的人是不是还能选
              let index = 0
              for (let v of res.data) {
                if (v.userid == userid) {
                  this.myValue = userid
                  break
                }
                // 1.2. 说明上次选的人不能选了, 给默认第一个人
                if (index == res.data.length - 1) {
                  console.error('上次选的人不能选了userid -> ', userid)
                  setCandiddataUser(this.variable, null)
                  this.myValue = res.data[0].userid
                }
                index++
              }
            } else {
              // 2. 缓存没有默认选中第一个
              this.myValue = res.data[0].userid
            }
            setCandiddataUser(this.variable, this.myValue)
            this.$emit('f_setVariable', this.variable, this.myValue)
          }
          this.candidateList = res.data
        }
        console.log('候选组', res, this.candidateList)
      })
    },
  },
}
</script>

@/utils/custom/custom-candidate.js